import { Injectable } from '@angular/core'
import { action, computed, observable } from 'mobx-angular'
import * as R from 'ramda'
import { autorun } from 'mobx'

const S_KEY = 'savedTransactions'

@Injectable()
export class Account {
  @observable transactions: number[] = []

  constructor() {
    if (localStorage.getItem(S_KEY)) {
      this.transactions = JSON.parse(localStorage.getItem(S_KEY))
    }
    autorun(() => {
      localStorage.setItem(S_KEY, JSON.stringify(this.transactions))
    })
  }

  @computed get balance(): number {
    return R.sum(this.transactions)
  }

  @computed get isNegative(): boolean {
    return this.balance < 0
  }

  @computed get deposits(): number[] {
    return this.transactions.filter(t => t >= 0)
  }

  @computed get withdrawls(): number[] {
    return this.transactions.filter(t => t < 0)
  }

  @action deposite(money: number) {
    if (money) {
      this.transactions = [ ...this.transactions, money ]
    }
  }

  @action withdraw(money: number) {
    if (money) {
      this.transactions = [ ...this.transactions, -money ]
    }
  }
}
